import axios from "axios";
import Vue from "vue";
import {getUserId} from "@/utils/UserCookies";
import {isUndefined} from "element-ui/src/utils/types";

const root = process.env.API_ROOT;

// 访问配置
const instance = axios.create({
  headers: {
    "Content-Type": "application/json; charset=UTF-8"
  },
  baseURL: root,
  transformRequest: [function (data) {
    if (isUndefined(data)){
      data = {userId: getUserId()}
    } else if (!data.userId){
      data.userId = getUserId();
    }
    return JSON.stringify(data);
  }],
  transformResponse: [function (data) {
    return data
  }],
  responseType: 'json',
  timeout: 30000,
});
// GET、POST请求
export default {
  post: function (url, data) {
    return instance
      .post(url, data)
      .then(res => res.data)
      .catch(handleError)
  },
  get: function (url, data) {
    return instance
      .get(url, {
        params: data
      })
      .then(res => res.data)
      .catch(handleError)
  }
}
// 请求失败
function handleError () {
  Vue.prototype.$message.error('请求远程服务器失败，请稍后再试')
}
